<template>
  <el-card>
    <el-form inline>
      <el-form-item style="margin-right: 20px">
        <el-input
          v-model="originInpValue"
          size="small"
          placeholder="用户名"
        ></el-input>
      </el-form-item>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-search"
        style="margin-top: 15px; font-size: 14px"
        @click="searchUser"
        >查询</el-button
      >
      <el-button
        @click="resetSearch"
        size="small"
        style="margin-top: 15px; font-size: 14px"
        >清空</el-button
      >
    </el-form>
    <el-button
      style="margin-top: 15px; font-size: 14px"
      type="primary"
      size="small"
      @click="showAddDialog"
      >添 加</el-button
    >
    <el-button
      style="font-size: 14px"
      type="danger"
      size="small"
      :disabled="!idList.length"
      @click="removeCheckedIdList"
      >批量删除</el-button
    >
    <!-- 表格 -->
    <el-table
      border
      :data="userList.items"
      ref="multipleTable"
      tooltip-effect="dark"
      style="width: 100%; margin: 20px 0px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" label="序号" width="80"> </el-table-column>
      <el-table-column prop="username" label="用户名" width="120">
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" width="300">
      </el-table-column>
      <el-table-column prop="roleName" label="角色列表"> </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间"> </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间"> </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row, $index }">
          <el-button
            @click="showRoles(row)"
            type="info"
            title="分配角色"
            size="mini"
            icon="el-icon-user-solid"
          ></el-button>
          <el-button
            @click="showUpdateDialog(row)"
            type="primary"
            title="修改用户"
            size="mini"
            icon="el-icon-edit-outline"
          ></el-button>
          <el-popconfirm
            style="margin-left: 10px"
            @onConfirm="deleteUser(row)"
            :title="`你确定要删除${row.username}吗`"
          >
            <el-button
              slot="reference"
              type="danger"
              title="删除用户"
              size="mini"
              icon="el-icon-delete"
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/修改弹框区域 -->
    <!-- :before-close="handleClose" -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input size="small" v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input size="small" v-model="ruleForm.nickName"></el-input>
        </el-form-item>
        <el-form-item v-if="!ruleForm.id" label="用户密码" prop="password">
          <el-input size="small" v-model="ruleForm.password"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="addOrUpdateUserInfo('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配角色弹框区域 -->
    <!-- :before-close="handleClose" -->
    <el-dialog title="设置角色" :visible.sync="dialogVisible1" width="50%">
      <el-form label-width="100px">
        <el-form-item label="用户名">
          <el-input size="small" disabled :value="role.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="userRoleIds"
            @change="handleCheckedRolesChange"
          >
            <el-checkbox
              v-for="role in roleOptions"
              :label="role.id"
              :key="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="saveAssignRoles"
          >保存</el-button
        >
        <el-button size="small" @click="dialogVisible1 = false">取消</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizechange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-size="limit"
      :pager-count="7"
      layout="prev, pager, next,jumper,->,sizes,total"
      :total="total"
      :page-sizes="[3, 5, 7, 10]"
      lang="cn"
    >
    </el-pagination>
  </el-card>
</template>
<script>
import { Message, MessageBox } from "element-ui";
import { mapState, mapGetters } from "vuex";
export default {
  name: "User",
  data() {
    // 验证密码正则
    // var validatePass = (rule, value, callback) => {
    //   let reg = /^\w{6,20}/;
    //   if (!value.test(reg)) {
    //     callback(new Error("请输入6-20位密码"));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      page: 1,
      limit: 5,
      total: 10,
      searchUsername: "", //查询时输入的用户名称
      originInpValue: "", //input框输入的原本数据
      dialogVisible: false, //对话框开关
      ruleForm: {
        //表单验证区域
        username: "", //添加/修改收集用户名称
        nickName: "", //收集用户昵称
        password: "", //收集用户密码
      },
      idList: [], //收集选中的用户id
      dialogVisible1: false, //控制角色弹框区域的显示
      role: {
        id: "",
        username: "", //角色弹框的用户信息
      },
      checkAll: false, //是否全部选中
      // roles: this.roleOptions, //角色列表
      isIndeterminate: true, //中间状态
      roleOptions: [], //角色列表
      userRoleIds: [], //用户自己的角色id列表

      // 验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "长度在 6 到 20 个字符",
            trigger: "change",
          },
        ],
      },
    };
  },

  mounted() {
    this.getUserList();
    // console.log(this.page, this.limit, this.searchUsername);
  },

  methods: {
    // 获取用户分页列表
    async getUserList() {
      let result = await this.$store.dispatch("userSetting/getUserList", {
        page: this.page,
        limit: this.limit,
        username: this.searchUsername,
      });
      this.total = result; //改变总数量
    },
    // 分页页码改变时的回调
    handleCurrentChange(page) {
      this.page = page;
      this.getUserList();
    },
    //每页显示数量改变时的回调
    handleSizechange(limit) {
      this.limit = limit;
      this.getUserList();
    },

    // 点击查询用户
    searchUser() {
      this.searchUsername = this.originInpValue;
      this.getUserList();
    },

    // 点击清空用户
    resetSearch() {
      this.searchUsername = "";
      this.originInpValue = "";
      this.getUserList();
    },
    // 点击添加弹框,添加用户
    showAddDialog() {
      this.dialogVisible = true;
      this.ruleForm = {}; //点击添加将userInfo信息置为空
    },

    // 点击修改弹框,修改用户信息
    showUpdateDialog(row) {
      this.dialogVisible = true;
      this.ruleForm = { ...row };
    },

    // 点击确定,发送添加/修改用户的请求,并校验输入的合法性
    addOrUpdateUserInfo(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.dispatch("userSetting/addOrUpdate", this.ruleForm);
          this.dialogVisible = false;
          this.getUserList();
        } else {
          Message.warning("校验失败");
        }
      });
    },

    // 删除用户

    deleteUser(row) {
      this.$store.dispatch("userSetting/removeUser", row.id);
      this.getUserList(this.userList.length > 1 ? this.page : this.page - 1);
    },

    //批量删除用户,收集用户选中的id到id数组中,使用reduce方法
    handleSelectionChange(val) {
      this.idList = val.reduce((prev, item) => {
        if (item.id) {
          prev.push(item.id);
        }
        return prev;
      }, []);
      console.log(this.idList);
    },

    //批量删除用户,使用messageBox
    removeCheckedIdList() {
      MessageBox.confirm("此操作删除的很多,三思而后行", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // this.$store.dispatch("userSetting/removeCheckedUser", this.idList);
          this.idList.forEach(async (item) => {
            await this.$store.dispatch("userSetting/removeUser", item);
          });
          if (this.page !== 1) {
            //判断批量删除是不是在第一页,如果不是判断长度
            this.getUserList(
              this.userList.length > 1 ? this.page : this.page - 1
            );
          } else {
            //如果是第一页,直接获取用户列表即可
            this.getUserList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 点击弹框展示分配角色对话框
    async showRoles(row) {
      this.dialogVisible1 = true;
      // 先清空选中角色信息
      this.userRoleIds = [];
      //得到用户角色列表
      let result = await this.$store.dispatch(
        "userSetting/getUserRoles",
        row.id
      );
      console.log("role的结果是", result);
      this.role = row; //输入框input的禁用文字
      this.roleOptions = result.allRolesList;
      result.assignRoles.forEach((item) => {
        this.userRoleIds.push(item.id);
      });
      console.log("userRoleIds的值是", this.userRoleIds);
    },

    // checkbox事件处理
    handleCheckAllChange(val) {
      // console.log("checkallchange的值是", val);
      // 如果为全选,将用户id收集成所有的id,否则置空
      this.userRoleIds = val ? this.roleOptions.map((item) => item.id) : [];
      this.isIndeterminate = false;
    },
    // 中间状态
    handleCheckedRolesChange(value) {
      // console.log("CheckedRolesChange值是", value);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roleOptions.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.roleOptions.length;
    },

    //点击保存发请求,分配角色
    saveAssignRoles() {
      this.dialogVisible1 = false;
      this.$store.dispatch("userSetting/assignRoles", {
        userId: this.role.id,
        roleIdList: this.userRoleIds,
      });
      // 分配角色成功后再次获取用户列表
      this.getUserList(this.page > 1 ? this.page : 1);
    },
  },

  computed: {
    ...mapState("userSetting", ["userList"]),
  },
};
</script>

<style scoped></style>
